package com.mairuide.phone.eachothercall;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.phone.abnormalphone.AbnormalPhoneParams;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.utils.D3;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.httpclient.BaseSite;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.callanalysis.entity.PhoneMapDetail;
import com.mairuide.phone.trackevents.TrackEventsService;

/**
 * 相互通话
 * @author mh
 *
 */
@Controller
@RequestMapping("/eachOtherCall")
public class EachOtherCallAnalysisController extends BaseController {
	
	@Resource
	private EachOtherCallAnalysisService eachOtherCallAnalysisService;
	
	@Resource
	private DataOperationLogService dataOperationLogService;

	/**
	 * 相互通话入口
	 * @param model
	 * @param eocap
	 * @return
	 */
	@ModuleCode(pValue = "eachOther", value = "caMC")
	@RequestMapping(value = "/eachOtherCallInit", method = RequestMethod.GET)
	public Object init(ModelMap model,EachOtherCallAnalysisParams eocap) {
		model.addAttribute("eca",null);
		model.addAttribute("eocap",eocap);
		model.addAttribute("title", null);
		model.addAttribute("phones", null);
		return "/phone/eachohter/eachOtherCallAnalysis";
	}
	
	/**
	 * 相互通话分析d3入口
	 * @return
	 */
	@RequestMapping(value = "/eachOtherCallAnalysisD3Init", method = RequestMethod.GET)
	public Object eachOtherCallAnalysisD3Init() {
		return "/phone/eachohter/eachOtherD3";
	}
	
	
	/**
	 * 相互通话分析
	 * @param model
	 * @param eocap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/eachOtherCallAnalysis", method = RequestMethod.POST)
	public Object eachOtherCallAnalysis(ModelMap model,@RequestBody EachOtherCallAnalysisParams eocap) {
		List<Object> result = new ArrayList<>();
		List<EachOtherCallAnalysis> eca = eachOtherCallAnalysisService.getEachOtherCallAnalysisList(eocap);
		/* 嫌疑人手机号码集合 */
		List<String> phones = new ArrayList<>();
		List<Map<String,Object>> foote = new ArrayList<>();
		for(String phoneNumber : eocap.getCheckedPhone().split(",")) {
			phones.add(phoneNumber);
            Map<String,Object> map = new HashMap<>();
			List<EachOtherCallAnalysis> collect = eca.stream().filter((EachOtherCallAnalysis e) -> e.getSuspectPhone().equals(phoneNumber)).collect(Collectors.toList());
            List<EachOtherCallAnalysisPersonal> ecaps = collect.get(0).getEcaps();
            int sumCallNumber = ecaps.stream().mapToInt(EachOtherCallAnalysisPersonal::getCallNumber).sum();
            int sumCallSeconds = ecaps.stream().mapToInt(EachOtherCallAnalysisPersonal::getCallSeconds).sum();
            map.put("suspectPhone",phoneNumber);
            map.put("totalCallNumber",sumCallNumber);
            map.put("totalCallSeconds",sumCallSeconds);
            foote.add(map);
		}
        int sumCallNumber = eca.stream().mapToInt(EachOtherCallAnalysis::getTotalCallNumber).sum();
        int sumCallSeconds = eca.stream().mapToInt(EachOtherCallAnalysis::getTotalCallSeconds).sum();
        Map<String,Object> map = new HashMap<>();
        map.put("suspectPhone","sum");
        map.put("totalCallNumber",sumCallNumber);
        map.put("totalCallSeconds",sumCallSeconds);
        foote.add(map);
        //eachOtherCallAnalysisService.getD3Result(eocap);
		model.addAttribute("eca",eca);

		result.add(phones);
        result.add(eca);
        result.add(foote);
        return SUCCESS(result);
    }
	
	/**
	 * 相互通话分析  d3
	 * @param eocap
	 * @return
	 */
    @ResponseBody
    @RequestMapping(value="/eachOtherCallAnalysis_d3",method= RequestMethod.POST)
    public Object eachOtherCallAnalysis_d3(EachOtherCallAnalysisParams eocap){
    	List<EachOtherCallAnalysis> ecas = eachOtherCallAnalysisService.getEachOtherCallAnalysisList(eocap);
		Map<String, Object> result = eachOtherCallAnalysisService.getD3Result(ecas);
		return result;
    }
	
	/**
	 * 相互通话详情跳转
	 * @param model
	 * @param eocap
	 * @return
	 */
	@RequestMapping(value = "/eachOtherDetailsInit", method = RequestMethod.GET)
	public Object eachOtherDetailsInit(ModelMap model, EachOtherCallAnalysisParams eocap) {
		model.addAttribute("callNumber", eocap.getCallNumber());
		model.addAttribute("startTime", eocap.getStartTime());
		model.addAttribute("endTime", eocap.getEndTime());
		model.addAttribute("suspectPhone", eocap.getSuspectPhone());
		model.addAttribute("caseId", eocap.getCaseId());
		model.addAttribute("suspectPhonePersonal", eocap.getSuspectPhonePersonal());
		return "/phone/eachohter/eachOtherDetails";
	}
	
	/**
	 * 相互通话-通话详情
	 * @param model
	 * @param eocap
	 * @return
	 */
	@RequestMapping(value = "/eachOtherDetails", method = RequestMethod.POST)
	@ResponseBody
	public Object eachOtherDetails(ModelMap model, EachOtherCallAnalysisParams eocap, Integer page,Integer rows, String sort, String order) {
		Page<PhoneRecord> pageCall = eachOtherCallAnalysisService.eachOtherDetails(eocap, new PageRequest(page-1, rows), sort, order);

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pageCall.getTotalElements());
		result.put("rows", pageCall.getContent());
		return result;
	}
	@RequestMapping(method= RequestMethod.POST,value = "eachOtherDetailsExcel")
	@ResponseBody
	public void findDealFlowListExcel(@RequestBody EachOtherCallAnalysisParams eocap, String sort, String order, HttpServletResponse response )throws Exception{
		XSSFWorkbook workbook1 = new XSSFWorkbook();
		SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
		//创建HSSFWorkbook对象(excel的文档对象)
		//建立新的sheet对象（excel的表单）
		Sheet sheet=wb.createSheet("通话详情");
		//在sheet里创建第二行
		Row row2=sheet.createRow(0);
		//创建单元格并设置单元格内容
		row2.createCell(0).setCellValue("机主号码");
		row2.createCell(1).setCellValue("呼叫类型");
		row2.createCell(2).setCellValue("对方号码");
		row2.createCell(3).setCellValue("通话日期");
		row2.createCell(4).setCellValue("通话时长");
		row2.createCell(5).setCellValue("基站号(CI)");
		row2.createCell(6).setCellValue("小区号(LAC)");
		row2.createCell(7).setCellValue("地址");
		//在sheet里创建第三行
		Page<PhoneRecord> pagePh = eachOtherCallAnalysisService.eachOtherDetails(eocap, new PageRequest(0, Integer.MAX_VALUE), sort, order);
		List<PhoneRecord> content = pagePh.getContent();
		if (content!=null && content.size()>0){
			for (int i=0;i<content.size();i++){
				PhoneRecord map = content.get(i);
				Row row3=sheet.createRow(i+1);
				row3.createCell(0).setCellValue(map.getServiceNumber());
				row3.createCell(1).setCellValue(map.getCallType()==0?"主叫":"被叫");
				row3.createCell(2).setCellValue(map.getPartyNumber());
				row3.createCell(3).setCellValue(DateUtils.getDateString(map.getStartingTime()));
				row3.createCell(4).setCellValue(map.getTalkTime());
				row3.createCell(5).setCellValue(map.getCid());
				row3.createCell(6).setCellValue( map.getLac());
				row3.createCell(7).setCellValue(map.getAddress());
			}
		}
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fileName = "通话详情" + dateFormat.format(new Date());
		//输出Excel文件
		OutputStream output=response.getOutputStream();
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
		response.setContentType("application/msexcel");
		wb.write(output);
		output.close();
		//添加导出日志
		dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

	}


	/**
     * 相互通话户导出excel
	 * @throws Exception 
     */
    @RequestMapping("/exportCallAnalysis")
    @ResponseBody
    public void exportCallAnalysis(HttpServletResponse response, EachOtherCallAnalysisParams eocap) throws Exception {

        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "相互通话分析" + dateFormat.format(date);
        
        String caseId = request.getSession().getAttribute("caseId") == null ? "" : request.getSession().getAttribute("caseId").toString();
		eocap.setCaseId(caseId);
		List<EachOtherCallAnalysis> ecas = eachOtherCallAnalysisService.getEachOtherCallAnalysisList(eocap);
		/* 嫌疑人手机号码集合 */
		List<String> phones = new ArrayList<>();
		List<String> title = new ArrayList<>();
		title.add("嫌疑人/嫌疑人");
		for(String phoneNumber : eocap.getCheckedPhone().split(",")) {
			phones.add(phoneNumber);
			title.add(phoneNumber);
		}
		title.add("汇总累计");
		 //设置导出Excel标题
        String[] titles = title.toArray(new String[title.size()]);
        List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
        if(null != phones && phones.size() > 0) {
        	for(String p : phones) {
        		Map<Integer, String> map = new HashMap<Integer, String>();
        		//手机号
        		map.put(0, p == null ? "" : p);
				if(null != ecas && !ecas.isEmpty()) {
					for (EachOtherCallAnalysis eca : ecas) {
						if (StringUtils.isNotEmpty(p) && p.equals(eca.getSuspectPhone())) {
							for(int i = 0 ; i < eca.getEcaps().size() ; i++) {
								if(eca.getEcaps().get(i).getCallNumber() > 0) {
									StringBuffer sbf = new StringBuffer();
									sbf.append("通话"+ eca.getEcaps().get(i).getCallNumber());
									sbf.append("次累计"+eca.getEcaps().get(i).getCallSeconds());
									sbf.append("秒"+eca.getEcaps().get(i).getBeginTime());
									sbf.append("-"+eca.getEcaps().get(i).getEndTime());
									map.put(i+1, sbf.toString());
								}else {
									map.put(i+1, "X");
								}
							}
							if(eca.getTotalCallNumber() > 0) {
								StringBuffer sbf = new StringBuffer();
								sbf.append("共通话 "+ eca.getTotalCallNumber());
								sbf.append("次累计"+eca.getTotalCallSeconds());
								sbf.append("秒"+eca.getTotalBeginTime());
								sbf.append("-"+eca.getTotalEndTime());
								map.put(eca.getEcaps().size()+1, sbf.toString());
							}
						}
					}
					lists.add(map);
				}
        	}
        	Map<Integer, String> map = new HashMap<Integer, String>();
        	map.put(0, "汇总累计");
        	for(String p : phones) {
        		if(null != ecas && !ecas.isEmpty()) {
					for(int i = 0; i < ecas.size(); i++ ) {
						if (StringUtils.isNotEmpty(p) && p.equals(ecas.get(i).getSuspectPhone())) {
							if(ecas.get(i).getTotalCallNumber() > 0) {
								StringBuffer sbf = new StringBuffer();
								sbf.append("共通话 "+ ecas.get(i).getTotalCallNumber());
								sbf.append("次累计"+ecas.get(i).getTotalCallSeconds());
								sbf.append("秒"+ecas.get(i).getTotalBeginTime());
								sbf.append("-"+ecas.get(i).getTotalEndTime());
								map.put(i+1, sbf.toString());
							}else {
								map.put(i+1, "X");
							}
						}
					}
					map.put(ecas.size()+1, "X");
        		}
        	}
        	lists.add(map);
        }

		//插入导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.EACHOTHER, ActionType.EXPORT);
        // 把导出的内容写入到流里面
        byte[] content = ExcelUtil.writeExcel(titles, lists);
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
}
